//
//  NetHandle.m
//
//  Created by Suns孙泉 on 14/12/4.
//  Copyright (c) 2014年 Suns. All rights reserved.
//

#import "NetHandle.h"

@implementation NetHandle

+(void)getDataWithURLString:(NSString *)URLString completion:(void (^)(NSData *))block{
    
    NSString *urlStr = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"GET";
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        // 处理数据
        // 确定地址
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [NSString stringWithFormat:@"%@/%ld", docPath, [URLString hash]];
        
        if (data != nil) {
            
            // 当返回的数据不是空, 就调用block.
            BOOL result = [NSKeyedArchiver archiveRootObject:data toFile:path];
            NSLog(@"存储成功: %d", result);
            
            block(data);
            
        }else{
            
            // 没有网络/请求失败 就从本地读取最近的一次成功数据
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil) {
                
                // 确保有数据才返回
                block(pickData);
                
            }
  
        }
        
        // 让有关视图 刷新数据
        // [tableView reloadData];
        // label.text = .....
        
    }];

}

@end
